package com.jerry.secondkill.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jerry.secondkill.dao.OrderDao;
import com.jerry.secondkill.domain.Order;
import com.jerry.secondkill.domain.SeckillOrder;
import com.jerry.secondkill.domain.User;
import com.jerry.secondkill.redis.RedisService;
import com.jerry.secondkill.redis.key.OrderKey;
import com.jerry.secondkill.vo.GoodsVo;

@Service
public class OrderService {
	
	@Autowired
	OrderDao orderDao;
	@Autowired
	RedisService redisService;
	
	public SeckillOrder getSeckillOrderByUserIdGoodsId(long userId, long goodsId) {
		return orderDao.getSeckillOrderByUserIdGoodsId(userId, goodsId);
	}

	public Order getOrderById(long orderId) {
		return orderDao.getOrderById(orderId);
	}
	
	@Transactional
	public Order createOrder(User user, GoodsVo goods) {
		//创建订单
		Order orderInfo = new Order();
		orderInfo.setCreateDate(new Date());
		orderInfo.setDeliveryAddrId(0L);
		orderInfo.setGoodsCount(1);
		orderInfo.setGoodsId(goods.getId());
		orderInfo.setGoodsName(goods.getGoodsName());
		orderInfo.setGoodsPrice(goods.getSeckillPrice());
		orderInfo.setOrderChannel(1);
		orderInfo.setStatus(0);
		orderInfo.setUserId(user.getId());
		orderDao.insertOrder(orderInfo);
		
		//创建秒杀订单
		SeckillOrder seckillOrder = new SeckillOrder();
		seckillOrder.setGoodsId(goods.getId());
		seckillOrder.setOrderId(orderInfo.getId());
		seckillOrder.setUserId(user.getId());
		orderDao.insertSeckillOrder(seckillOrder);
		
		redisService.set(OrderKey.getSeckillOrderByUidGid, ""+user.getId()+"_"+goods.getId(), seckillOrder);
		
		return orderInfo;
	}
	
	public void deleteOrders() {
		orderDao.deleteOrders();
		orderDao.deleteSeckillOrders();
	}
	
}
